package com.tanhua.dubbo.api.impl.mongo;
import com.tanhua.domain.vo.PageResult;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.dubbo.api.mongo.FriendApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service(timeout = 200000)
public class FriendApiImpl implements FriendApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     *
     * @param userId 用户id
     * @param friendId 好友id
     */
    @Override
    public void addContacts(Long userId, Long friendId) {
        // 构造条件，进行判断：如果不是好友则执行保存
        Query query = new Query(
                Criteria.where("userId").is(userId)
                .and("friendId").is(friendId)
        );
        // 没有查询到好友关系，执行保存
        if (!mongoTemplate.exists(query,Friend.class)) {
            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            // 保存好友关系
            mongoTemplate.insert(friend);
        }

        // 处理好友的双向关系
        query = new Query(
                Criteria.where("userId").is(friendId)
                        .and("friendId").is(userId)
        );
        if (!mongoTemplate.exists(query,Friend.class)) {
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setCreated(System.currentTimeMillis());
            // 保存好友关系
            mongoTemplate.insert(friend);
        }
    }

    @Override
    public PageResult findByPage(Integer page, Integer pagesize, Long userId) {
        // 构造条件：查询登陆用户的好友列表
        Query query = Query.query(
                Criteria.where("userId").is(userId)
        );
        // 分页
        query.limit(pagesize).skip((page-1)*pagesize);
        // 条件分页查询
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);
        // 统计
        long count = mongoTemplate.count(query, Friend.class);
        return new PageResult(page,pagesize, (int) count,friendList);
    }

    /**
     * 查询用户的好友
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public List<Friend> queryUserFriend(Long userId) {
        Query query = new Query(Criteria.where("userid").is(userId));
        List<Friend> friendList = mongoTemplate.find(query, Friend.class);

        return friendList;
    }
}
